package com.pubinfo.passbook.common.service.master.impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.mychain.gov.sdk.base.enums.InvoiceTypeEnum;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pubinfo.passbook.common.annotation.RequiredLog;
import com.pubinfo.passbook.common.entity.TFileInfo;
import com.pubinfo.passbook.common.entity.TSourceInvoice;
import com.pubinfo.passbook.common.entity.TSourceInvoiceItem;
import com.pubinfo.passbook.common.entity.TSystemRole;
import com.pubinfo.passbook.common.mapper.TFileInfoMapper;
import com.pubinfo.passbook.common.mapper.TSourceInvoiceMapper;
import com.pubinfo.passbook.common.mapper.TSubsidiaryPrivateKeyMapper;
import com.pubinfo.passbook.common.model.dto.tax.InvoicePageParamObj;
import com.pubinfo.passbook.common.model.vo.InvoiceList;
import com.pubinfo.passbook.common.model.vo.base.MyPage;
import com.pubinfo.passbook.common.service.master.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.pubinfo.passbook.common.model.constant.RoleEnum.ADMIN;

/**
 *
 */
@Slf4j
@Service
public class TInvoiceServiceImpl extends ServiceImpl<TSourceInvoiceMapper, TSourceInvoice> implements TInvoiceService {
  @Resource
  TSourceCarInvoiceService carInvoiceService;
  @Resource
  TSourceNormalService normalService;
  @Resource
  TSourceSecondHandCarInvoiceService handCarInvoiceService;
  @Resource
  TSourceInvoiceItemService itemService;
  
  @Autowired
  private TSubsidiaryPrivateKeyMapper keyMapper;
  
  @Autowired
  TSystemTaskLogService taskLogService;

  @Autowired
  TFileInfoMapper tFileInfoMapper;

  @Autowired
  TSystemRoleService tSystemRoleService;
  
  @RequiredLog("发票列表查询")
  @Override
  public MyPage<InvoiceList> listTInvoice(InvoicePageParamObj paramObj, TSystemRole role) {
    //默认排序
    if (StringUtils.isEmpty(paramObj.getCurrent())) {
      paramObj.setCurrent(1L);
    }
    MyPage<InvoiceList> myPage = new MyPage<>(paramObj);
    List<InvoiceList> list;
    Long totalPage = 0L;
    
    if (role == null) {
      //普通用户不查询发票
      return null;
    } else {
      if (!ADMIN.getRoleCode().equals(role.getRoleCode())) {
        //部门报账员 医药费审核员查询所在公司的发票
        paramObj.setDistrictId(role.getDistrictId());
      }
  
      list = this.baseMapper.listTInvoiceByDep(paramObj);
    }
    totalPage = this.baseMapper.findInvoiceCount(paramObj);
    if (totalPage == 0) {
      return myPage;
    }
    Long pageCount = (totalPage - 1) / paramObj.getSize() + 1;
    myPage.setCountPage(pageCount);
    myPage.setTotalItem(totalPage);
    myPage.setData(list);
    return myPage;
  }
  
  @Override
  public JSONObject detailsInvoiceById(String id) {
    TSourceInvoice invoiceDetail=this.baseMapper.selectById(id);
    if (StringUtils.isEmpty(invoiceDetail)) {
      return null;
    }
    List<TFileInfo> tFileInfos=tFileInfoMapper.selectByInvoiceId(id);
    tFileInfos.addAll(tFileInfoMapper.selectByFPKEY(id));
    JSONObject jsonObject=new JSONObject(invoiceDetail.getDataJson());
    jsonObject.put("tFileInfos",tFileInfos);
    return jsonObject;
  }
  
  @Transactional
  @Override
  public Integer deleteByLogId(String logId) {
    //查询所有发票
    QueryWrapper<TSourceInvoice> queryWrapper = new QueryWrapper<>();
    queryWrapper.eq("log_id", logId);
    List<TSourceInvoice> list = this.baseMapper.selectList(queryWrapper);
    
    if (CollectionUtils.isEmpty(list)) {
      return 0;
    }
    List<String> ids = list.stream().map(TSourceInvoice::getId).collect(Collectors.toList());
    //删除商品表
    QueryWrapper<TSourceInvoiceItem> itemQueryWrapper = new QueryWrapper<>();
    itemQueryWrapper.in("parent_id", ids);
    itemService.remove(itemQueryWrapper);
    carInvoiceService.removeByIds(ids);
    normalService.removeByIds(ids);
    handCarInvoiceService.removeByIds(ids);
    removeByIds(ids);
    return ids.size();
  }
  
  @Transactional
  @Override
  public Boolean deleteInvoiceById(String id) {
    //先删除商品表,再根据类型,删除相应发票,再删除源发票.
    if (StringUtils.isEmpty(id)) {
      return false;
    }
    TSourceInvoice sourceInvoice = getById(id);
    InvoiceTypeEnum typeEnum = InvoiceTypeEnum.getByCode(sourceInvoice.getFplx());
    switch (typeEnum) {
      //机动车
      case JDCFP:
        carInvoiceService.removeById(id);
        break;
      //二手车
      case ESCFP:
        handCarInvoiceService.removeById(id);
        break;
      //普通发票
      default:
        normalService.removeById(id);
    }
    QueryWrapper<TSourceInvoiceItem> itemQueryWrapper = new QueryWrapper<>();
    itemQueryWrapper.eq("parent_id", id);
    itemService.remove(itemQueryWrapper);
    
    return removeById(id);
  }
  
  @Override
  public Integer batchDeleteInvoiceByIds(List<String> ids) {
    //先删除商品表,再根据类型,删除相应发票,再删除源发票.
    if (CollectionUtils.isEmpty(ids)) {
      return 0;
    }
    List<TSourceInvoice> invoiceList = listByIds(ids);
    if (CollectionUtils.isEmpty(invoiceList)) {
      return 0;
    }
    Map<String, List<TSourceInvoice>> fplxMap = invoiceList.stream().collect(Collectors.groupingBy(TSourceInvoice::getFplx));
    if (!fplxMap.isEmpty()) {
      for (String key : fplxMap.keySet()) {
        InvoiceTypeEnum typeEnum = InvoiceTypeEnum.getByCode(key);
        List<TSourceInvoice> invoiceListValue = fplxMap.get(key);
        List<String> invoiceIds = invoiceListValue.stream().map(TSourceInvoice::getId).collect(Collectors.toList());
        switch (typeEnum) {
          //机动车
          case JDCFP:
            carInvoiceService.removeByIds(invoiceIds);
            break;
          //二手车
          case ESCFP:
            handCarInvoiceService.removeByIds(invoiceIds);
            break;
          //普通发票
          default:
            normalService.removeByIds(invoiceIds);
        }
      }
    }
    
    QueryWrapper<TSourceInvoiceItem> itemQueryWrapper = new QueryWrapper<>();
    itemQueryWrapper.in("parent_id", ids);
    itemService.remove(itemQueryWrapper);
    removeByIds(ids);
    return ids.size();

  }
  
}

